package cn.smileyan.demos.operators;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * 例子4： keyBy 例子
 * @author smileyan
 */
public class KeyByDemo {
    public static void main(String[] args) throws Exception {
        final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<Tuple2<Integer, String>> items = env.fromElements(Tuple2.of(1, "hello"),
                Tuple2.of(2, "welcome"), Tuple2.of(1, "flink"), Tuple2.of(2, "to"), Tuple2.of(2, "China"));

        SingleOutputStreamOperator<String> output = items.keyBy(tuple -> tuple.f0)
                .flatMap(new FlatMapFunction<Tuple2<Integer, String>, String>() {
                    @Override
                    public void flatMap(Tuple2<Integer, String> tuple, Collector<String> collector) throws Exception {
                        collector.collect(tuple.f1 + " ");
                    }
                });

        output.print();

        env.execute("Flink KeyBy Example");
    }
}
